package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink07_Timer_Exec_WithKeyedState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据,并转为JavaBean,然后将相同的id的数据聚和到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .keyBy("id");


        //3.实现需求
        /**
         * 监控水位传感器的水位值，
         * 如果水位值在五秒钟之内连续上升，(保留上一次水位值,将当前水位值和上一次水位值做对比，看是否上升，需要注册一个5秒的定时器，如果没有上升则重置定时器，如果连续上升，则什么也不做等定时器触发，然后报警)
         * 则报警，并将报警信息输出到侧输出流。
         */
        SingleOutputStreamOperator<String> process = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //定义一个变量用来保存上一次水位
//            private Integer lastVc = Integer.MIN_VALUE;
            private ValueState<Integer> lastVc;

            //定义一个变量用来保存定时器的时间
//            private Long timer = Long.MIN_VALUE;
            private ValueState<Long> timer;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastVc = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVc", Integer.class,Integer.MIN_VALUE));

                timer = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer", Long.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.判断水位是否上升
//                if (value.getVc() > lastVc) {
                if (value.getVc() > lastVc.value()) {
                    //2.如果没有注册定时器的话注册一个定时器
//                    if (timer == Long.MIN_VALUE) {
                    if (timer.value() == null) {
                        //没有注册定时器
                        //3.注册定时器
                        System.out.println("注册定时器："+ctx.getCurrentKey());
//                        timer = ctx.timerService().currentProcessingTime() + 5000;
                        long curTimer = ctx.timerService().currentProcessingTime() + 5000;
                        timer.update(curTimer);
                        ctx.timerService().registerProcessingTimeTimer(curTimer);
                    }
                } else {
                    //水位没有上升
                    //4.取消之前已经注册过的定时器
                    System.out.println("删除定时器："+ctx.getCurrentKey());
                    ctx.timerService().deleteProcessingTimeTimer(timer.value());

                    //5.为了方便下次水位上升时注册定时器你，因此要把定时时间恢复默认值
//                    timer = Long.MIN_VALUE;
                    timer.clear();
                }
                //6.无论水位是否变化，都要保存起来
//                lastVc = value.getVc();
                lastVc.update(value.getVc());
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //定时器报警，重置定时器
//                timer = Long.MIN_VALUE;
                timer.clear();

                //获取侧输出流，将报警信息发送至侧输出
                ctx.output(new OutputTag<String>("output"){}, "警报！！！！水位连续5s上升");
            }
        });

        process.print("主流");

        process.getSideOutput(new OutputTag<String>("output") {
        }).print("警报");

        env.execute();
    }
}
